package org.skydiveapplibrary.repository;

import org.skydiveapplibrary.data.Database;
import org.skydiveapplibrary.data.Settings;
import org.skydiveapplibrary.data.UnitOfMeasure;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public class SettingsRepository
{
	// cached settings 
	private static Settings settings;
	
	// context
	private Database database;
	
	public SettingsRepository(Context context)
	{
		database = new Database(context);
	}
	
	public Settings getSettings()
	{
		// use cached value
		if (settings != null)
		{
			return settings;
		}
		
		SQLiteDatabase db = database.getReadableDatabase();
		Cursor cursor = null;
		try
		{
			// perform query
			cursor = db.query(
					Database.SETTINGS_TABLE,
					Database.SETTINGS_ALL_COLUMNS,
					null, null, null, null, null);
			
			// get over results
			if (cursor.moveToFirst())
			{
				// get settings
				settings = new Settings();
				settings.setUnitOfMeasure(UnitOfMeasure.valueOf(Database.getString(cursor, Database.SETTINGS_UNIT_OF_MEASURE)));
				settings.setExitAltitude(Database.getInteger(cursor, Database.SETTINGS_EXIT_ALTITUDE));
				settings.setDeploymentAltitude(Database.getInteger(cursor, Database.SETTINGS_DEPLOYMENT_ALTITUDE));
			}
		}
		finally
		{
			// close cursor
			if (cursor != null)
			{
				cursor.close();
			}
			// close database
			db.close();
		}

		return settings;
	}
	
	public void updateSettings(Settings settings)
	{
		// update cached value
		SettingsRepository.settings = settings; 

		// get update values
		ContentValues values = new ContentValues();
		values.put(Database.SETTINGS_UNIT_OF_MEASURE, settings.getUnitOfMeasure().toString());
		values.put(Database.SETTINGS_EXIT_ALTITUDE, settings.getExitAltitude());
		values.put(Database.SETTINGS_DEPLOYMENT_ALTITUDE, settings.getDeploymentAltitude());
		
		SQLiteDatabase db = database.getWritableDatabase();
		try
		{
			// do update
			db.update(Database.SETTINGS_TABLE, values, null, null);
		}
		finally
		{
			// close db
			db.close();
		}
	}
}
